package org.catspaw.cherubim.persistence.jdbc.dbutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbutils.QueryRunner;

public class InsertableQueryRunner extends QueryRunner {

	public Object insert(Connection conn, String sql, Object... params)
			throws SQLException {
		return insert(conn, sql, false, params);
	}

	public Object insert(Connection conn, String sql,
			boolean autoGeneratedKeys, Object... params) throws SQLException {
		PreparedStatement stmt = null;
		ResultSet keys = null;
		try {
			if (autoGeneratedKeys) {
				stmt = conn
						.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			} else {
				stmt = conn.prepareStatement(sql);
			}
			fillStatement(stmt, params);
			stmt.executeUpdate();
			if (autoGeneratedKeys) {
				keys = stmt.getGeneratedKeys();
				if (keys.next()) {
					return keys.getObject(1);
				}
			}
			return null;
		} catch (SQLException e) {
			rethrow(e, sql, params);
		} finally {
			close(stmt);
			close(keys);
		}
		return null;
	}
}
